package com.ibpd.henuocms.web.controller.manage;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.util.TextUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.dao.impl.HqlParameter;
import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.dao.impl.HqlParameter.DataType_Enum;
import com.ibpd.entity.baseEntity.IBaseEntity;
import com.ibpd.henuocms.assist.OrderMap;
import com.ibpd.henuocms.assist.PermissionModelEntity;
import com.ibpd.henuocms.common.IbpdCommon;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.ListSortUtil;
import com.ibpd.henuocms.common.Pinyin4jUtil;
import com.ibpd.henuocms.common.RandomUtil;
import com.ibpd.henuocms.common.SysUtil;
import com.ibpd.henuocms.common.TxtUtil;
import com.ibpd.henuocms.entity.ContentEntity;
import com.ibpd.henuocms.entity.NodeAttrEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.NodeFormEntity;
import com.ibpd.henuocms.entity.NodeFormFieldEntity;
import com.ibpd.henuocms.entity.PageTemplateEntity;
import com.ibpd.henuocms.entity.StyleTemplateEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.entity.ext.NodeExtEntity;
import com.ibpd.henuocms.entity.ext.NodeFormExtEntity;
import com.ibpd.henuocms.entity.ext.PageTemplateExtEntity;
import com.ibpd.henuocms.entity.ext.TreeNodeEntity;
import com.ibpd.henuocms.entity.ext.TreeNodeUtil;
import com.ibpd.henuocms.service.content.ContentServiceImpl;
import com.ibpd.henuocms.service.content.IContentService;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.nodeAttr.INodeAttrService;
import com.ibpd.henuocms.service.nodeAttr.NodeAttrServiceImpl;
import com.ibpd.henuocms.service.nodeForm.INodeFormService;
import com.ibpd.henuocms.service.nodeForm.NodeFormServiceImpl;
import com.ibpd.henuocms.service.pageTemplate.IPageTemplateService;
import com.ibpd.henuocms.service.pageTemplate.PageTemplateServiceImpl;
import com.ibpd.henuocms.service.styleTemplate.IStyleTemplateService;
import com.ibpd.henuocms.service.styleTemplate.StyleTemplateServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.henuocms.web.controller.ext.FormModel;
@Controller
public class Node extends BaseController {
	@RequestMapping("Manage/Node/index.do")
	public String index(String id,Model model,HttpServletRequest req) throws IOException{
		model.addAttribute("nodeId",id);
		if(id.indexOf("_")==-1){
			model.addAttribute("loginedUserType",SysUtil.getCurrentLoginedUserType(req.getSession()));
			model.addAttribute("permissionEnable_nodeAdd",SysUtil.checkPermissionIsEnable(req.getSession(), "node_add", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeEdit",SysUtil.checkPermissionIsEnable(req.getSession(), "node_edit", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeDel",SysUtil.checkPermissionIsEnable(req.getSession(), "node_del", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeReload",SysUtil.checkPermissionIsEnable(req.getSession(), "node_reload", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeMove",SysUtil.checkPermissionIsEnable(req.getSession(), "node_move", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeOrder",SysUtil.checkPermissionIsEnable(req.getSession(), "node_order", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodePubThis",SysUtil.checkPermissionIsEnable(req.getSession(), "node_pub_this", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodePubCnt",SysUtil.checkPermissionIsEnable(req.getSession(), "node_pub_cnt", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodePubNew",SysUtil.checkPermissionIsEnable(req.getSession(), "node_pub_new", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeOpenClose",SysUtil.checkPermissionIsEnable(req.getSession(), "node_open_close", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeNaviHidden",SysUtil.checkPermissionIsEnable(req.getSession(), "node_navi_hidden", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeSearch",SysUtil.checkPermissionIsEnable(req.getSession(), "node_search", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
	
			model.addAttribute("permissionEnable_contDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "cont_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_tempDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "template_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeFormDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "nodeform_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contFormDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "contform_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_nodeRecycleDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "node_recycle_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_contRecycleDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "cont_recycle_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_keyDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "key_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_acDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "ac_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
			model.addAttribute("permissionEnable_tagDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "tag_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
		}else{
			id=id.split("_")[1];
			model.addAttribute("permissionEnable_nodeAdd",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_add", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeEdit",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_edit", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeDel",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_del", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeReload",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_reload", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeMove",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_move", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeOrder",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_order", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodePubThis",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_pub_this", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodePubCnt",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_pub_cnt", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodePubNew",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_pub_new", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeOpenClose",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_open_close", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeNaviHidden",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_navi_hidden", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeSearch",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_search", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			
			model.addAttribute("permissionEnable_contDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "cont_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_tempDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "template_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeFormDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "nodeform_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contFormDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "contform_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_nodeRecycleDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "node_recycle_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_contRecycleDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "cont_recycle_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_keyDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "key_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_acDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "ac_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
			model.addAttribute("permissionEnable_tagDisp",SysUtil.checkPermissionIsEnable(req.getSession(), "tag_disp", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_SITE));
		}
		return "manage/node/index";
	}
	@RequestMapping("Manage/Node/tree.do")
	public void tree(String id,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		Long nodeId=null;
		Long siteId=null;
		if(id==null){
			nodeId=null;
		}else if(id.split("_").length==2){
			String t=id.split("_")[1];
			if(StringUtil.isNumeric(t)){
				siteId=Long.parseLong(t);
				nodeId=-1L;
			}else if(t.trim().toLowerCase().equals("all")){
				siteId=-99L;
			}else{
				siteId=-1L;
			} 
		}else{
			if(StringUtil.isNumeric(id)){
				nodeId=Long.parseLong(id);
			}
		}
		//如果nodeId==-1，取站点信息
		String rtnJson="";
		ISubSiteService siteService=(ISubSiteService) this.getService(SubSiteServiceImpl.class);
		if(nodeId==null){
//			siteService.getDao().clearCache();
			List<SubSiteEntity> siteList=siteService.getList();
			if(siteList!=null){
				rtnJson="[{\"id\":\"site_all\",\"text\":\"所有站点\",\"children\":[";
				for(SubSiteEntity site:siteList){  
					rtnJson+="{\"id\":\"site_"+site.getId()+"\",\"text\":\""+site.getSiteName()+"\",\"iconCls\":\"icon-save\",\"state\":\"closed\"},";
				} 
				rtnJson=rtnJson.substring(0,rtnJson.length()-1)+"]}]";
			}
//			rtnJson="[{\"id\":-1,\"text\":\""+SysUtil.getSiteName()+"\",\"iconCls\":\"icon-save\", \"children\":"+rtnJson+"}]";			
		}else{ 
			nodeId=(nodeId==null)?-1L:nodeId; 
			
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
//			nodeService.getDao().clearCache();
			NodeEntity n=nodeService.getEntityById(nodeId);
			if(n!=null){
				siteId=n.getSubSiteId();
			}
			List<HqlParameter> pList=new ArrayList<HqlParameter>();
			pList.add(new HqlParameter("id",nodeId,null));
			pList.add(new HqlParameter("subSiteId",siteId,null));
			pList.add(new HqlParameter("isDeleted",false,DataType_Enum.Boolean));
			List<NodeEntity> nodeList=nodeService.getList("from "+nodeService.getTableName()+" where parentId=:id and subSiteId=:subSiteId and isDeleted=:isDeleted",pList,"order asc",-1,-1);
			List<TreeNodeEntity> treeNodeList=TreeNodeUtil.converToTreeNode(nodeList);
			JSONArray jsonArray = JSONArray.fromObject( treeNodeList );
			rtnJson=jsonArray.toString();
		}
		PrintWriter out = resp.getWriter();
		 out.print(rtnJson);
		 out.flush();
	}
	@RequestMapping("Manage/Node/siteNodeTree.do")
	public void siteNodeTree(String id,Long siteId,Boolean returnLeafNode,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(siteId==null || siteId<=0L){
			super.printJsonData(resp, "[]");
			return;
		}
		returnLeafNode=(returnLeafNode==null)?true:returnLeafNode;
		String rtnJson="";
		ISubSiteService siteService=(ISubSiteService) this.getService(SubSiteServiceImpl.class);
		if(id==null){
			SubSiteEntity site=siteService.getEntityById(siteId);
			if(site!=null){
				rtnJson+="[{\"id\":\"site_"+site.getId()+"\",\"text\":\""+site.getSiteName()+"\",\"iconCls\":\"icon-save\",\"state\":\"closed\"}]";
			}
		}else{ 
			if(id.split("_").length==2){
				id="-1";
			}
			Long nodeId=Long.valueOf(id);
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			
			List<HqlParameter> pList=new ArrayList<HqlParameter>();
			pList.add(new HqlParameter("id",nodeId,null));
			pList.add(new HqlParameter("subSiteId",siteId,null));
			pList.add(new HqlParameter("isDeleted",false,DataType_Enum.Boolean));
			String hql="from "+nodeService.getTableName()+" where parentId=:id and subSiteId=:subSiteId and isDeleted=:isDeleted";
			if(returnLeafNode){
				hql=hql+" and leaf=true";
			}
			List<NodeEntity> nodeList=nodeService.getList(hql,pList,"order asc",-1,-1);
			List<TreeNodeEntity> treeNodeList=TreeNodeUtil.converToTreeNode(nodeList);
			JSONArray jsonArray = JSONArray.fromObject( treeNodeList );
			rtnJson=jsonArray.toString();
		}
		PrintWriter out = resp.getWriter();
		 out.print(rtnJson);
		 out.flush();
	}
	@RequestMapping("Manage/Node/list.do")
	public void list(String id,HttpServletResponse resp,String order,Integer page,Integer rows,String sort,String queryString,HttpServletRequest req) throws IOException{
		INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
		String ss[]=id.split("_");
		String query="";
		if(ss.length==2){
			query="subSiteId="+ss[1]+" and parentId=-1";
		}else{
			query="parentId="+id;
		}
		if(queryString!=null && !queryString.trim().equals("")){
			query+=" and text like '%"+queryString.trim()+"%'";
		}
		query+=" and isDeleted=false"; 
		IbpdLogger.getLogger(this.getClass()).info(order+"\n"+sort);
		super.getList(req, nodeService, resp, order, page, rows, sort, query);
	}
	@RequestMapping("Manage/Node/toOrder.do")
	public String toOrder(String ids,Model model,HttpServletRequest req){
		List<NodeEntity> orderNodeList=new ArrayList<NodeEntity>();
		if(StringUtil.isBlank(ids)){
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
		String[] idss=ids.split(",");
		Long parentId=null;
		Long siteId=-1L;
		for(String id:idss){
			if(StringUtil.isNumeric(id)){
				orderNodeList.add(nodeServ.getEntityById(Long.valueOf(id)));
			}
		}
		model.addAttribute("orderNodeList",orderNodeList);
		parentId=(orderNodeList.size()==0)?-1L:orderNodeList.get(0).getParentId();
		siteId=(orderNodeList.size()==0)?-1L:orderNodeList.get(0).getSubSiteId();
		if(parentId!=null){
			List<NodeExtEntity> nodesList=nodeServ.getChildNodeList(siteId, parentId, 100, 0, "order", "desc");
			model.addAttribute("nodes",nodesList);
		}
		return "manage/node/order";
	}
	@RequestMapping("Manage/Node/doOrder.do")
	public void doOrder(OrderMap map,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(map!=null || !map.getoMap().isEmpty()){
			INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
			Long parentNodeId=null;
			String key=map.getoMap().keySet().toArray()[0].toString();
			if(!StringUtil.isBlank(key)){
				NodeEntity node=nodeServ.getEntityById(Long.valueOf(key));
				if(node!=null){
					parentNodeId=node.getParentId();
				}
			}
			if(parentNodeId==null){
				printParamErrorMsg(resp);
				return;
			}
			List<NodeEntity> nodeList=nodeServ.getList("from "+nodeServ.getTableName()+" where parentId="+parentNodeId, null);
			//先把同级别的栏目取出来，然后将栏目的排序值重新编排，间隔为10，也就是说，默认栏目管理页面的栏目列表中最多支持9个栏目调整顺序
			Map<Long,NodeEntity> tmpMap=new LinkedHashMap<Long,NodeEntity>();
			for(Integer i=0;i<nodeList.size();i++){
				NodeEntity cn=nodeList.get(i);
				cn.setOrder((i+1)*10);
				tmpMap.put(cn.getId(), cn);
			}
			//tmpMap为临时存放ID和实体的map，为了方便调用
			//下面将前台取过来的kv值进行处理
			for(String k:map.getoMap().keySet()){
				String v=map.getoMap().get(k);
				if(!StringUtil.isBlank(v)){
					NodeEntity en=tmpMap.get(Long.valueOf(k));
					if(v.equals("-1")){
						en.setOrder(1);
					}else if(v.equals("-99")){
						en.setOrder(10000);
					}else{
						NodeEntity tn=tmpMap.get(Long.valueOf(v));
						if(tn!=null && en!=null){
							en.setOrder(tn.getOrder()+1);
						}	
					}
				}
			}
			//清空弄的List，将新的排序的nodeEntity存进去，然后更新排序值
			nodeList.clear();
			for(Long _id:tmpMap.keySet()){
				nodeList.add(tmpMap.get(_id));
			}
			
			ListSortUtil<NodeEntity> sortUtil=new ListSortUtil<NodeEntity>();
			sortUtil.sort(nodeList, "order", "asc");
			for(Integer j=0;j<nodeList.size();j++){
				NodeEntity n=nodeList.get(j);
				n.setOrder(j+1);
				System.out.println(n.getId()+"\t"+n.getText()+"\t"+n.getOrder());
				nodeServ.saveEntity(n);
			}
			printDefaultSuccessMsg(resp);
		}else{
			printParamErrorMsg(resp);
		}
	}
	@RequestMapping("Manage/Node/toImport.do")
	public String toImport(String nodeId,Model model,HttpServletRequest req){
		model.addAttribute("nodeId",nodeId);
		return "manage/node/import";
	}
	@RequestMapping("Manage/Node/doImport.do")
	public void doImport(String nodeId,HttpServletRequest req,HttpServletResponse resp,Model model) throws IOException{
		if(nodeId==null){
			super.printMsg(resp, "-1", "-1", "参数缺失");
			return;
		}
		String siteId="";
		if(nodeId.split("_").length==2){
			siteId=nodeId.split("_")[1];
			nodeId=null;
		}
		NodeEntity node=null;
		String uploadPath=req.getRealPath("/uploadFiles/");
		INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
		INodeAttrService nodeAttrServ=(INodeAttrService) getService(NodeAttrServiceImpl.class);
		if(nodeId!=null){
			node=nodeServ.getEntityById(Long.valueOf(nodeId));
		}else{
			node=new NodeEntity();
			node.setSubSiteId(Long.valueOf(siteId));
			node.setDepth(0);
			node.setParentId(-1L);
			node.setNodeIdPath(",");
			node.setId(-1L);
		}
		if(node!=null){
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置内存缓冲区，超过后写入临时文件
			factory.setSizeThreshold(10240000);
			// 设置临时文件存储位置
			
			String basePath = uploadPath;
			File fbasePath = new File(basePath);
			if(!fbasePath.exists())
				fbasePath.mkdirs();
				factory.setRepository(fbasePath);
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置单个文件的最大上传值
				upload.setFileSizeMax(1024*1024*100);
				// 设置整个request的最大值
				upload.setSizeMax(1024*1024*100*20);
				upload.setHeaderEncoding("UTF-8");
				
				try {
					List<?> items = upload.parseRequest(req);
					FileItem item = null;
					String fileName = null;
						item = (FileItem) items.get(0);
						String newFileName=item.getName()+"_"+RandomUtil.randomString(10)+".csv";
						fileName = basePath + File.separator + newFileName;
						if (!item.isFormField() && item.getName().length() > 0){
							item.write(new File(fileName));
						}
						String nodeTexts=TxtUtil.readTxtFile(fileName,"GB2312");
						nodeTexts=nodeTexts.replace("\r", "");
						String[] spNodeText=nodeTexts.split("\n");
						for(String nodeText:spNodeText){
							String[] subNodeField=nodeText.split(",");
							if(subNodeField.length>=4){
								String nodeTitle=subNodeField[0];
								String nodeState=subNodeField[1];
								String navi=subNodeField[2];
								String url=subNodeField[3];
								NodeEntity n=new NodeEntity();
								n.setSubSiteId(node.getSubSiteId());
								n.setParentId(node.getId());
								n.setDepth(node.getDepth()+1);
								n.setText(nodeTitle);
								n.setState((nodeState.toLowerCase().trim().equals("Y")?NodeEntity.NODESTATE_OPEN:NodeEntity.NODESTATE_CLOSE));
								n.setNodeType((url.toLowerCase().trim().length()>0)?NodeEntity.NODETYPE_LOCAL:NodeEntity.NODETYPE_REDIRECT);
								n.setIsDeleted(false);
								n.setLinkUrl(n.getNodeType()==NodeEntity.NODETYPE_REDIRECT?url:"");
								n.setCreateDate(new Date());
								n.setCreateUser(SysUtil.getCurrentLoginedUserName(req.getSession()));
								nodeServ.saveEntity(n);
								n.setNodeIdPath(node.getNodeIdPath()+n.getId()+",");
								nodeServ.saveEntity(n);
								NodeAttrEntity na=new NodeAttrEntity();
								na.setCommentpageTemplateId(-1L);
								na.setCommentStyleTemplateId(-1L);
								na.setContentpageTemplateId(-1L);
								na.setContentStyleTemplateId(-1L);
								na.setDirectory(Pinyin4jUtil.getPinYinHeadChar(n.getText()));
								na.setDisplayInNavigator(navi.toLowerCase().trim().equals("y")?true:false);
								na.setNodeId(n.getId());
								na.setNodePageTemplateId(-1L);
								na.setNodeStyleTemplateId(-1L);
								na.setOrderByNavigator(99);
								na.setTemplateGroupId(-1L);
								nodeAttrServ.saveEntity(na);
							}
						}
						super.printMsg(resp, "99", "99", "导入完成");
						return;
				} catch (FileUploadException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}				
		}
		super.printMsg(resp, "-1", "-1", "参数缺失");
	}
	@RequestMapping("Manage/Node/toExport.do")
	public String toExport(String ids,Model model,HttpServletRequest req){
		return "manage/node/export";
	}
	@RequestMapping("Manage/Node/toMove.do")
	public String toMove(String ids,Model model,HttpServletRequest req){
		List<NodeEntity> moveNodeList=new ArrayList<NodeEntity>();
		if(StringUtil.isBlank(ids)){
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
		String[] idss=ids.split(",");
		for(String id:idss){
			if(StringUtil.isNumeric(id)){
				moveNodeList.add(nodeServ.getEntityById(Long.valueOf(id)));
			}
		}
		if(moveNodeList==null || moveNodeList.size()==0){
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return super.ERROR_PAGE;
		}
		model.addAttribute("moveNodeList",moveNodeList);
		model.addAttribute("currentSiteId",moveNodeList.get(0).getSubSiteId());
		return "manage/node/move";
	}
	@RequestMapping("Manage/Node/doMove.do")
	public void doMove(OrderMap map,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		//逻辑：根据传值的KV键值对，取出要移动的栏目ID和移动目标栏目的ID，然后检索出移动栏目的所有子栏目以及下面的内容，更新自身和子栏目、内容的 nodeId,parentId,nodeIdPath，保存之,最后将目标栏目的leaf置为true即可
		if(map!=null || !map.getoMap().isEmpty()){
			INodeService nodeServ=(INodeService) getService(NodeServiceImpl.class);
			IContentService contServ=(IContentService) getService(ContentServiceImpl.class);
			for(String key:map.getoMap().keySet()){
				String vkey=map.getoMap().get(key);
				if(vkey.split("_").length>1){
					vkey="-1";
				}
				if(StringUtil.isNumeric(key) && !StringUtil.isBlank(vkey)){
					NodeEntity sourceNode=nodeServ.getEntityById(Long.valueOf(key));
					NodeEntity targetNode=null;
					if(vkey.equals("-1")){
						targetNode=new NodeEntity();
						targetNode.setId(-1L);
						targetNode.setNodeIdPath(",");
						targetNode.setDepth(0);
					}else{
						targetNode=nodeServ.getEntityById(Long.valueOf(vkey));
					}
					if(sourceNode!=null && targetNode!=null){
						//先改sourceNode的相关信息，包括子栏目和内容
						String targetNodeIdPath=targetNode.getNodeIdPath()+""+sourceNode.getId()+",";
						//先更新内容
						List<ContentEntity> contList=contServ.getContentListByNodeId(sourceNode.getId(), 99999, 0, "order", "asc");
						if(contList!=null){
							for(ContentEntity c:contList){
								String[] spNodeIdPaths=c.getNodeIdPath().split(","+sourceNode.getId()+",");
								if(spNodeIdPaths.length==2){
									c.setNodeIdPath(targetNodeIdPath+spNodeIdPaths[1]);
								}else if(spNodeIdPaths.length==1){
									c.setNodeIdPath(targetNodeIdPath);
								}
								
								contServ.saveEntity(c);
							}
						}
						//更新本身栏目的idpath
						sourceNode.setNodeIdPath(targetNodeIdPath);
						sourceNode.setParentId(targetNode.getId());
						sourceNode.setDepth(targetNode.getDepth()+1);
						nodeServ.saveEntity(sourceNode);
						//更新子栏目
						List<NodeEntity> childNodeList=nodeServ.getChildNodeList( sourceNode.getId());
						if(childNodeList!=null){
							for(NodeEntity node:childNodeList){
								String[] spNodeIdPath=node.getNodeIdPath().split(","+sourceNode.getId()+",");
								if(spNodeIdPath.length==2){
									node.setNodeIdPath(targetNodeIdPath+spNodeIdPath[1]);
									node.setDepth(sourceNode.getDepth()+1);
									nodeServ.saveEntity(node);
								}
							}
						}
					}
				}
			}
			printDefaultSuccessMsg(resp);
		}else{
			printParamErrorMsg(resp);
		}
	}
	@RequestMapping("Manage/Node/props.do")
	public String props(String id,Model model,HttpServletRequest req){
		if(id==null || id.trim().length()==0){
			model.addAttribute(ERROR_MSG,MSG_PARAMERROR_MSG);
			return this.ERROR_PAGE;
		}
		List<PageTemplateExtEntity> sitePageTemplateList=null;
		List<StyleTemplateEntity> siteStyleTemplateList=null;
		List<PageTemplateExtEntity> nodePageTemplateList=null;
		List<StyleTemplateEntity> nodeStyleTemplateList=null;
		List<PageTemplateExtEntity> contentpageTemplateList=null;
		List<StyleTemplateEntity> contentStyleTemplateList=null;
		List<PageTemplateExtEntity> commentpageTemplateList=null;
		List<StyleTemplateEntity> commentStyleTemplateList=null;
		IPageTemplateService pageTempServ=(IPageTemplateService) getService(PageTemplateServiceImpl.class);
		sitePageTemplateList=pageTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", "type="+PageTemplateEntity.TEMPLATE_TYPE_SITE);
		nodePageTemplateList=pageTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", "type="+PageTemplateEntity.TEMPLATE_TYPE_NODE);
		contentpageTemplateList=pageTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", "type="+PageTemplateEntity.TEMPLATE_TYPE_CONTENT);
		commentpageTemplateList=pageTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", "type="+PageTemplateEntity.TEMPLATE_TYPE_COMMENT);
		
		IStyleTemplateService styleTempServ=(IStyleTemplateService) getService(StyleTemplateServiceImpl.class);
		siteStyleTemplateList=styleTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", null);
		nodeStyleTemplateList=siteStyleTemplateList;//styleTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", null);
		contentStyleTemplateList=siteStyleTemplateList;//styleTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", null);
		commentStyleTemplateList=siteStyleTemplateList;//styleTempServ.getList(SysUtil.getManagedSiteIds(), null, 1000, 0, "order asc", null);
		model.addAttribute("sitePageTemplateList",sitePageTemplateList);
		model.addAttribute("siteStyleTemplateList",siteStyleTemplateList);
		model.addAttribute("nodePageTemplateList",nodePageTemplateList);
		model.addAttribute("nodeStyleTemplateList",nodeStyleTemplateList);
		model.addAttribute("contentpageTemplateList",contentpageTemplateList);
		model.addAttribute("contentStyleTemplateList",contentStyleTemplateList);
		model.addAttribute("commentpageTemplateList",commentpageTemplateList);
		model.addAttribute("commentStyleTemplateList",commentStyleTemplateList);
	String ss[]=id.split("_");
		String query="";
		if(ss.length==2){
			String sid=ss[1];
			if(StringUtil.isNumeric(sid)){
				Long siteId=Long.parseLong(sid);
				ISubSiteService siteService=(ISubSiteService) this.getService(SubSiteServiceImpl.class);
				SubSiteEntity site=siteService.getEntityById(siteId);
				model.addAttribute("site",site);
			}
			model.addAttribute("permissionEnable",SysUtil.checkPermissionIsEnable(req.getSession(), "site_node_prop_save", Long.valueOf(sid),PermissionModelEntity.MODEL_TYPE_SITE));
			return "manage/subSite/props";
		}
		if(StringUtil.isNumeric(id)){
			Long nodeId=Long.parseLong(id);
			if(nodeId!=null && !nodeId.equals("-1")){
				INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
				NodeEntity node=nodeService.getEntityById(nodeId);
				if(node!=null){
					model.addAttribute("node",node);
					System.out.println("node.text="+node.getText());
					INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
//					nfService.getDao().clearCache();
					NodeFormExtEntity nodeForm=nfService.getNodeForm(NodeFormEntity.FORMTYPE_NODEFORM, nodeId,null);
					if(nodeForm==null){
						nodeForm=nfService.getDefaultNodeFormExtEntity(NodeFormEntity.FORMTYPE_NODEFORM);
//						model.addAttribute(ERROR_MSG,"该栏目没有设置表单");
//						return super.ERROR_PAGE;
					}
					model.addAttribute("fields",(nodeForm!=null)?nodeForm.getNodeFormFieldList():nodeForm);
					model.addAttribute("permissionEnable",SysUtil.checkPermissionIsEnable(req.getSession(), "node_prop_save", Long.valueOf(id),PermissionModelEntity.MODEL_TYPE_NODE));
					INodeAttrService attrService=(INodeAttrService) ServiceProxyFactory.getServiceProxy(NodeAttrServiceImpl.class);
					NodeAttrEntity attr=attrService.getNodeAttr(nodeId);
					model.addAttribute("attr",attr);
				}
			}
		} 
		return "manage/node/props";
	}	
	@RequestMapping("Manage/Node/init.do")
	public void init(HttpServletResponse resp) throws Exception{
		INodeService ns=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
		ns.initNodeDemo();
		super.printJsonData(resp, "ok");
	}
	@RequestMapping("Manage/Node/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException{
		if(id!=null && id!=-1){
			String[] tmp=field.split("_");
			if(tmp.length==1){
				INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
				NodeEntity node=nodeService.getEntityById(id);
				if(node!=null){
					//先确定参数类型
					Method tmpMethod=node.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
					
					
					Method method=node.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					method.invoke(node, val);
					nodeService.saveEntity(node);
//					nodeService.getDao().clearCache();
					this.makeStaticPage(MakeType.栏目, id, null, null);
				}
			}else{
				if(tmp.length==2){
					String fld=tmp[1];
					INodeAttrService attrService=(INodeAttrService) ServiceProxyFactory.getServiceProxy(NodeAttrServiceImpl.class);
					NodeAttrEntity attr=attrService.getNodeAttr(id);
					Method tmpMethod=attr.getClass().getMethod("get"+fld.substring(0,1).toUpperCase()+fld.substring(1), new Class[]{});				
					Method method=attr.getClass().getMethod("set"+fld.substring(0,1).toUpperCase()+fld.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					method.invoke(attr, val);
					attrService.saveEntity(attr);
//					attrService.getDao().clearCache();
					this.makeStaticPage(MakeType.栏目, id, null, null);
				}else{
					super.printMsg(resp,"-4", "-4", MSG_PARAMERROR_MSG);
				}
			}
		}
	}
	@RequestMapping("Manage/Node/publishNode.do")
	public void publishNode(Long id,HttpServletResponse resp){
		this.makeStaticPage(MakeType.栏目, id, null, null);
	}
	@RequestMapping("Manage/Node/publishContent.do")
	public void publishContent(Long id,HttpServletResponse resp){
		if(id!=null && id!=-1){
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			NodeEntity node=nodeService.getEntityById(id);
			if(node!=null){
				String idpath=node.getNodeIdPath();
				Long siteId=node.getSubSiteId();
				this.makeStaticPage(MakeType.站点, siteId, null, null);
				String[] ids=idpath.split(NodeEntity.NODEIDPATH_SPLIT);
				IContentService contentServ=(IContentService) getService(ContentServiceImpl.class);
				for(String nid:ids){
					if(StringUtil.isNumeric(nid)){
						this.makeStaticPage(MakeType.栏目, Long.parseLong(nid), null, null);
						List<ContentEntity> cList=contentServ.getContentListByNodeId(Long.parseLong(nid), 1000, 0, "id", "desc");
						for(ContentEntity ce:cList){
							this.makeStaticPage(MakeType.内容, ce.getId(), null, null);
						}
						
					}
				}
			}
		}
	}
	@RequestMapping("Manage/Node/publishTree.do")
	public void publishTree(Long id,Boolean publishContent,HttpServletResponse resp){
		publishContent=publishContent==null?false:publishContent;
		if(id!=null && id!=-1){
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			NodeEntity node=nodeService.getEntityById(id);
			if(node!=null){
				String idpath=node.getNodeIdPath();
				Long siteId=node.getSubSiteId();
				this.makeStaticPage(MakeType.站点, siteId, null, null);
				String[] ids=idpath.split(NodeEntity.NODEIDPATH_SPLIT);
				IContentService contentServ=(IContentService) getService(ContentServiceImpl.class);
				for(String nid:ids){ 
					if(StringUtil.isNumeric(nid)){
						this.makeStaticPage(MakeType.栏目, Long.parseLong(nid), null, null);
						if(publishContent){
							List<ContentEntity> cList=contentServ.getContentListByNodeId(Long.parseLong(nid), 1000, 0, "id", "desc");
							for(ContentEntity ce:cList){
								this.makeStaticPage(MakeType.内容, ce.getId(), null, null);
								
							}
						}
					}
				}
			}
		}		
	} 
	@RequestMapping("Manage/Node/publishSite.do")
	public void publishSite(Long id,HttpServletResponse resp){
		if(id!=null && id!=-1){
			this.makeStaticPage(MakeType.站点, id, null, null);
		}		
	}
	@RequestMapping("Manage/Node/state.do")
	public void state(Long id,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id!=null && id!=-1){
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			NodeEntity node=nodeService.getEntityById(id);
			if(node!=null){
				node.setState(node.getState()==1?0:1);
				nodeService.saveEntity(node);
			}
		}
	}
		@RequestMapping("Manage/Node/navi.do")
		public void navi(Long id,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
			if(id!=null && id!=-1){
				INodeAttrService attrService=(INodeAttrService) getService(NodeAttrServiceImpl.class);
				NodeAttrEntity attr=attrService.getNodeAttr(id);
				if(attr!=null){
					attr.setDisplayInNavigator(!attr.getDisplayInNavigator());
					attrService.saveEntity(attr);
				}
			}
		
	}
		@RequestMapping("Manage/Node/toAdd.do")
		public String toAdd(String parentId,Model model,HttpServletResponse resp) throws IOException{
			if(StringUtils.isEmpty(parentId)){
				return this.ERROR_PAGE;
			}
			Long siteId=null;
			Long nId=null;
			if(parentId.indexOf("site_")!=-1){
				String t=parentId.replace("site_", "");
				if(StringUtil.isNumeric(t)){
					siteId=Long.parseLong(t);
					nId=-1L;
				}
			}else{
				nId=Long.parseLong(parentId);
			}
			model.addAttribute("parentId",nId);
			model.addAttribute("siteId",siteId);
			//在这个地方获取栏目默认的表单字段，然后前台显示,这里获取的字段要分组压入前台，前台根据group分别显示
			List<NodeFormFieldEntity> baseFieldList=new ArrayList<NodeFormFieldEntity>();
			List<NodeFormFieldEntity> viewFieldList=new ArrayList<NodeFormFieldEntity>();
			List<NodeFormFieldEntity> templateFieldList=new ArrayList<NodeFormFieldEntity>();
			INodeFormService formService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
			NodeFormExtEntity formField=null;
			if(nId==-1L){
				formField=formService.getDefaultNodeFormExtEntity(NodeFormEntity.FORMTYPE_NODEFORM);
			}else{
				formField=formService.getNodeForm(NodeFormEntity.FORMTYPE_NODEFORM, nId,null);
			}
			if(formField==null){
				super.printMsg(resp, "-1", "-1", "没有对应的表单.");
				return super.ERROR_PAGE;
			}
			List<NodeFormFieldEntity> fieldList=formField.getNodeFormFieldList();
			if(fieldList==null || fieldList.size()==0){
				super.printMsg(resp, "-2", "-1", "没有对应的字段.");
				return super.ERROR_PAGE;
			}
			for(NodeFormFieldEntity field:fieldList){
				if(field!=null){
					if(field.getGroup().toLowerCase().trim().equals("base")){
						baseFieldList.add(field);
					}else if(field.getGroup().toLowerCase().trim().equals("view")){
						viewFieldList.add(field);
					}else if(field.getGroup().toLowerCase().trim().equals("template")){
						templateFieldList.add(field);
					}
				}
			}
			model.addAttribute("base",baseFieldList);
			model.addAttribute("view",viewFieldList);
			model.addAttribute("template",templateFieldList);
			NodeAttrEntity attr=new NodeAttrEntity();
			model.addAttribute("attr",attr);
			return "manage/node/add";
		}
		@RequestMapping("Manage/Node/toEdit.do")
		public String toEdit(Long id,Model model,HttpServletResponse resp) throws IOException{
			if(id==null){
				return this.ERROR_PAGE;
			}
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
//			nodeService.getDao().clearCache();
			NodeEntity ne=nodeService.getEntityById(id);
			if(ne==null){
				return this.ERROR_PAGE;
			}
			model.addAttribute("nodeEntity",ne);
			//在这个地方获取栏目默认的表单字段，然后前台显示,这里获取的字段要分组压入前台，前台根据group分别显示
			List<NodeFormFieldEntity> baseFieldList=new ArrayList<NodeFormFieldEntity>();
			List<NodeFormFieldEntity> viewFieldList=new ArrayList<NodeFormFieldEntity>();
			List<NodeFormFieldEntity> templateFieldList=new ArrayList<NodeFormFieldEntity>();
			INodeFormService formService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
			NodeFormExtEntity formField=formService.getNodeForm(NodeFormEntity.FORMTYPE_NODEFORM, id,null);
			if(formField==null){
				super.printMsg(resp, "-1", "-1", "没有对应的表单.");
				return super.ERROR_PAGE;
			}
			List<NodeFormFieldEntity> fieldList=formField.getNodeFormFieldList();
			if(fieldList==null || fieldList.size()==0){
				super.printMsg(resp, "-2", "-1", "没有对应的字段.");
				return super.ERROR_PAGE;
			}
			for(NodeFormFieldEntity field:fieldList){
				if(field!=null){
					if(field.getGroup().toLowerCase().trim().equals("base")){
						baseFieldList.add(field);
					}else if(field.getGroup().toLowerCase().trim().equals("view")){
						viewFieldList.add(field);
					}else if(field.getGroup().toLowerCase().trim().equals("template")){
						templateFieldList.add(field);
					}
				}
			}
			model.addAttribute("base",baseFieldList);
			model.addAttribute("view",viewFieldList);
			model.addAttribute("template",templateFieldList);
			INodeAttrService attrService=(INodeAttrService) ServiceProxyFactory.getServiceProxy(NodeAttrServiceImpl.class);
			NodeAttrEntity attr=attrService.getNodeAttr(id);
			model.addAttribute("attr",attr);
			return "manage/node/edit";
		}
		@RequestMapping("Manage/Node/doEdit.do")
		public void doEdit(@FormModel("nodeEntity") NodeEntity nodeEntity,@FormModel("attrEntity") NodeAttrEntity attrEntity,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
			if(nodeEntity!=null && nodeEntity.getId()!=null && nodeEntity.getId()!=-1L){
//				System.out.println(nodeEntity.getId()+":"+nodeEntity.getOrder());
				INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
				NodeEntity ne=nodeService.getEntityById(nodeEntity.getId());
				if(ne==null){
					resp.getWriter().write("1202");
					resp.getWriter().flush();
				}else{
					swap(ne,nodeEntity);
					nodeService.saveEntity(ne);
//					nodeService.getDao().clearCache();
					INodeAttrService attrService=(INodeAttrService) getService(NodeAttrServiceImpl.class);
					NodeAttrEntity attr=attrService.getNodeAttr(nodeEntity.getId());
					attr.setCommentpageTemplateId(attrEntity.getCommentpageTemplateId());
					attr.setCommentStyleTemplateId(attrEntity.getCommentStyleTemplateId());
					attr.setContentpageTemplateId(attrEntity.getContentpageTemplateId());
					attr.setContentStyleTemplateId(attrEntity.getContentStyleTemplateId());
					attr.setDirectory(attrEntity.getDirectory());
					attr.setDisplayInNavigator(attrEntity.getDisplayInNavigator());
					attr.setNodeId(nodeEntity.getId());
					attr.setNodePageTemplateId(attrEntity.getNodePageTemplateId());
					attr.setNodeStyleTemplateId(attrEntity.getNodeStyleTemplateId());
					attr.setOrderByNavigator(attrEntity.getOrderByNavigator());
					attrService.saveEntity(attr);
//					attrService.getDao().clearCache();
					resp.getWriter().write("99");
					resp.getWriter().flush();
				}
			}else{
				resp.getWriter().write("1201");
				resp.getWriter().flush();
			}
			
		}
		private IBaseEntity swap(IBaseEntity dbEntity , IBaseEntity obEntity) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
			Method[] methods=obEntity.getClass().getMethods();
			for(Method getMethod:methods){
				String getMethodName=getMethod.getName();
				if(getMethodName.substring(0,3).equals("get") && !getMethodName.equals("getClass")){
					String setMethodName="set"+getMethodName.substring(3);
					Method setMethod=dbEntity.getClass().getMethod(setMethodName, getMethod.getReturnType());
					if(setMethod!=null){
						
						setMethod.invoke(dbEntity, getMethod.invoke(obEntity, null));
					}
				}
			}
			return dbEntity;
		}
		@RequestMapping("Manage/Node/doAdd.do")
		public void doAdd(@FormModel("nodeEntity") NodeEntity nodeEntity,@FormModel("attrEntity") NodeAttrEntity attrEntity,HttpServletRequest req,HttpServletResponse resp) throws IOException{
			if(nodeEntity.getParentId()==null){
				super.printMsg(resp, "-1", "-1", "parentId_is_null");
				return;
			}
			
			if(nodeEntity.getText().trim().equals("")){
				printParamErrorMsg(resp);
				return;
			}
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			NodeEntity parentNode=(nodeEntity.getParentId()!=-1L)?nodeService.getEntityById(nodeEntity.getParentId()):null;
			nodeEntity.setCreateDate(new Date());
			nodeEntity.setCreateUser(SysUtil.getCurrentLoginedUserName(req.getSession()));
			nodeEntity.setChildCount(0);
			nodeEntity.setCountentCount(0);
			nodeEntity.setDepth(parentNode!=null?parentNode.getDepth()+1:1);
			nodeEntity.setIsDeleted(false);
			nodeEntity.setLeaf(false); 
			nodeEntity.setNodeIdPath((nodeEntity!=null && nodeEntity.getParentId()!=-1L)? parentNode!=null?parentNode.getNodeIdPath():",":",");
			nodeEntity.setSubSiteId(parentNode!=null?parentNode.getSubSiteId():nodeEntity.getSubSiteId());
			nodeService.saveEntity(nodeEntity);
			if(nodeEntity.getId()>0){
				nodeEntity.setNodeIdPath(nodeEntity.getNodeIdPath()+nodeEntity.getId()+",");
				nodeService.saveEntity(nodeEntity);
			}else{
				System.out.println("nodeId is null");
			}
			List<HqlParameter> pList=new ArrayList<HqlParameter>();
			pList.add(new HqlParameter("id",nodeEntity.getParentId(),DataType_Enum.Long));
			Long rowCount=nodeService.getRowCount(" where isDeleted=false and parentId=:id", pList);
			if(parentNode!=null){
				parentNode.setChildCount(rowCount.intValue());
				if(!parentNode.getLeaf()){
					parentNode.setLeaf(true);
				}				
				nodeService.saveEntity(parentNode) ;	
				
			}
			
			//将node和form作对照
			INodeFormService formService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
			Long nfId=formService.getNodeFormId(NodeFormEntity.FORMTYPE_NODEFORM, (parentNode!=null)?parentNode.getId():-1L);
			formService.linkNodeForm(nodeEntity.getId(), nfId);  
			Long cfId=formService.getNodeFormId(NodeFormEntity.FORMTYPE_CONTENTFORM, (parentNode!=null)?parentNode.getId():-1L);
			formService.linkNodeForm(nodeEntity.getId(), cfId);  
			//保存 attr信息
			attrEntity.setNodeId(nodeEntity.getId());
			if(attrEntity.getDirectory()!=null || attrEntity.getDirectory().trim().equals("")){
				attrEntity.setDirectory(Pinyin4jUtil.getPinYinHeadChar(nodeEntity.getText()));
			}
			INodeAttrService attrService=(INodeAttrService) getService(NodeAttrServiceImpl.class);
			attrService.saveEntity(attrEntity);
			super.printMsg(resp, "99", "-1", "保存成功");
			 
		}
		/**
		 * 本来是计划用来更新字段值来着，结果也就用来 做更新“是否已经删除”字段的值了
		 * @param ids
		 * @param resp
		 * @throws NoSuchMethodException
		 * @throws SecurityException
		 * @throws IllegalAccessException
		 * @throws IllegalArgumentException
		 * @throws InvocationTargetException
		 */
	@RequestMapping("Manage/Node/recv.do")
	public void recv(String ids,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(ids!=null){
			String whereString=" where ";
			List<HqlParameter> pList=new ArrayList<HqlParameter>();
			if(ids.substring(ids.trim().length()-1).equals(",")){
				String[] id=ids.split(",");
				for(Integer i=0;i<id.length;i++){
					pList.add(new HqlParameter("id"+i,Long.parseLong(id[i]),DataType_Enum.Long));
					whereString+="id=:id"+i+" or ";
				}
			}
			whereString=whereString.substring(0,whereString.length()-4);
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			List<NodeEntity> nodeList=nodeService.getList("from "+nodeService.getTableName()+whereString,pList);
			if(nodeList!=null){
				List<HqlParameter> tList=new ArrayList<HqlParameter>();
				NodeEntity simpNode=null;
				IContentService contentService=(IContentService) ServiceProxyFactory.getServiceProxy(ContentServiceImpl.class);
				for(Integer i=0;i<nodeList.size();i++){
					NodeEntity ne=nodeList.get(i);
					ne.setIsDeleted(true);
					simpNode=simpNode==null?ne:simpNode;
					nodeService.saveEntity(ne);
					List<NodeEntity> nList=nodeService.getList("from "+nodeService.getTableName()+" where nodeIdPath like '%,"+ne.getId()+",%'",null);
					for(NodeEntity n:nList){
						n.setIsDeleted(true);
						nodeService.saveEntity(n);
					}
					List<ContentEntity> contentList=contentService.getList("from "+contentService.getTableName()+" where nodeIdPath like '%,"+ne.getId()+",%'",null);
					for(ContentEntity c:contentList){
						c.setDeleted(true);
						c.setLastUpdateDate(new Date());
						contentService.saveEntity(c);
					}
				}
				
				tList.add(new HqlParameter("id",simpNode.getParentId(),DataType_Enum.Long));
				List<NodeEntity> parentList=nodeService.getList("from "+nodeService.getTableName()+" where id=:id",tList);
				for(NodeEntity pn:parentList){
					pn.setChildCount(pn.getChildCount()>=nodeList.size()?pn.getChildCount()-nodeList.size():0);
					if(pn.getChildCount()==0){
						pn.setLeaf(false);
					}
					nodeService.saveEntity(pn);
				}
			}
		}
		
	}
}

